package com.mimosa.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {
	
	static final int BUFFER = 8192;

	private File zipFile;

	public ZipUtil(File zipFile) { 
		this.zipFile = zipFile; 
	}

	public void compress(List<String>  root) throws IOException { 
			FileOutputStream fileOutputStream = new FileOutputStream(zipFile); 
			CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, 
			new CRC32()); 
			ZipOutputStream out = new ZipOutputStream(cos);
			for(String s :root){
				compressFile(new File(s) , out );
			}
			out.close(); 
	}
	/** 压缩一个文件 */ 
	private void compressFile(File file, ZipOutputStream out ) { 
		if (!file.exists()) { 
			return; 
		} 
		try { 
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); 
			ZipEntry entry = new ZipEntry(file.getName()); 
			out.putNextEntry(entry); 
			int count; 
			byte bb[] = new byte[BUFFER]; 
			while ((count = bis.read(bb, 0, BUFFER)) != -1) { 
				out.write(bb, 0, count); 
			} 
			bis.close(); 
		} catch (Exception e) { 
			throw new RuntimeException(e); 
		} 
	} 
}
